﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace 图片转pdf咯by胖大海
{
    public partial class Form1 : Form
    {
        // string pathDrag;//存储鼠标拖动事件里面的拖拽文件数据
        // DragEventArgs eDrag;
        string OutPathTemp;//输出目录暂时
        public List<System.Drawing.Image> li = new List<System.Drawing.Image>();//暂时放图片
        string strLog =
            "开发日志："
            +"增加了转换完成后自动打开目录的功能。"
            +"消除在第一次点击生成按钮后,未消除的List导致的图片叠加问题。"
            +"消除了为解决图片叠加问题list设置为null后的空指针错误。"
            +"滚动条设置为最后"
            +"增加批量拖动图片功能"
            ;

        public Form1()
        {

            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listView1_DragDrop(object sender, DragEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

            //////////Document doc = new Document(PageSize.A4);//A4作为基准
            //////////doc.AddCreationDate();
            //////////doc.AddProducer();
            //////////doc.SetMargins(0, 0, 0, 0);//边距设置为0后就不必强制设定绝对坐标值了SetAbsolutePosition（10，20）;SetAbsolutePosition是从左下角算起的计算也不方便。自然A4大小边缘被裁剪的问题也消失了


            ////////////用当前时间作为pdf文件名
            ////////////因为使用“:”与“/”会出错“//”又懒得加
            //////////string strDataMilli =
            //////////    DateTime.Now.ToShortDateString().Replace('/', '-')
            //////////    + "-"
            //////////    + DateTime.Now.ToShortTimeString().Replace(':', '-')
            //////////    + "-"
            //////////    + DateTime.Now.Millisecond.ToString();
            ////////////MessageBox.Show(this, strDataMilli);//测试文件名合法性
            ////////////会有文件同时占用的情况
            //////////PdfWriter.GetInstance(doc, new FileStream("d:\\" + strDataMilli + ".pdf", FileMode.Create));

            ////////////PdfWriter.GetInstance(document, new FileStream("d:\\Chap0101.pdf", FileMode.Create));
            //////////iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("C:\\Users\\Administrator\\Desktop\\QQ浏览器截图\\QQ浏览器截图_20170308205813_DA2AAE39567A4d1e866903921E3555F2.jpg");
            //////////iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance("C:\\Users\\Administrator\\Desktop\\QQ浏览器截图\\QQ浏览器截图_20170308205813_DA2AAE39567A4d1e866903921E3555F2.jpg");
            //////////iTextSharp.text.Image img3 = iTextSharp.text.Image.GetInstance("C:\\Users\\Administrator\\Desktop\\QQ浏览器截图\\QQ浏览器截图_20170308205813_DA2AAE39567A4d1e866903921E3555F2.jpg");
            //////////iTextSharp.text.Image img4 = iTextSharp.text.Image.GetInstance("C:\\Users\\Administrator\\Desktop\\QQ浏览器截图\\QQ浏览器截图_20160718212943_3DFAB2DCA3A7416a9D0A50BE5BA14FC1.png");
            //////////img.ScalePercent(40);
            //////////img2.ScaleAbsoluteHeight(PageSize.A4.Height);//依Y轴拉伸
            //////////img3.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);//缩放到A4宽
            //////////img4.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);//缩放到A4宽

            ////////////图片变形要放在document的open()前,否则无效果！！！
            //////////doc.Open();
            ////////////doc.NewPage();//确保每页一张图片
            //////////doc.Add(img);
            //////////doc.NewPage();//确保每页一张图片
            //////////doc.Add(img2);
            //////////doc.NewPage();//确保每页一张图片
            //////////doc.Add(img3);
            //////////doc.NewPage();//确保每页一张图片
            //////////doc.Add(img4);//测试多页显示效果
            ////////////img2.ScaleAbsolute(PageSize.A4.Width,PageSize.A4.Height);           
            ////////////jpeg.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);
            ////////////img2.ScaleToFit(PageSize.A4.Width, PageSize.A4.Height);
            ////////////document.Add(new Paragraph("Hello World"));
            //////////doc.Close();
            //////////MessageBox.Show(this, "转换成功！");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //////////Document doc = new Document(PageSize.A4);//A4作为基准
            //////////doc.AddCreationDate();
            //////////doc.AddProducer();
            //////////doc.SetMargins(0, 0, 0, 0);//边距设置为0后就不必强制设定绝对坐标值了SetAbsolutePosition（10，20）;SetAbsolutePosition是从左下角算起的计算也不方便。自然A4大小边缘被裁剪的问题也消失了


            ////////////用当前时间作为pdf文件名
            ////////////因为使用“:”与“/”会出错“//”又懒得加
            //////////string strDataMilli =
            //////////    DateTime.Now.ToShortDateString().Replace('/', '-')
            //////////    + "-"
            //////////    + DateTime.Now.ToShortTimeString().Replace(':', '-')
            //////////    + "-"
            //////////    + DateTime.Now.Millisecond.ToString();
            ////////////输出路径名打包，方便后用
            //////////string strFileOutdirectory = 
            //////////    "d:\\" + strDataMilli + ".pdf";
            ////////////MessageBox.Show(this, strDataMilli);//测试文件名合法性
            ////////////会有文件同时占用的情况
            //////////PdfWriter.GetInstance(doc, new FileStream(strFileOutdirectory, FileMode.Create));

            //////////doc.Open();
            ////////////图片变形要放在document的open()前,否则无效果！！！
            //////////for (int i = 0; i <= imageList1.Images.Count - 1; i++)
            //////////{
            //////////    doc.NewPage();
            //////////    iTextSharp.text.Image imgTEMP = iTextSharp.text.Image.GetInstance(imageList1.Images[i], System.Drawing.Imaging.ImageFormat.Jpeg);
            //////////    //imgTEMP = iTextSharp.text.Image.GetInstance(PhotoImageInsert(imageList1.Images[i]));
            //////////    imgTEMP.ScaleToFit(PageSize.A4);
            //////////    doc.Add(imgTEMP);
            //////////}
            //////////doc.Close();
            //////////MessageBox.Show(this, "转换成功！");
            //////////richTextBox1.Text = richTextBox1.Text + System.Environment.NewLine + "转换成功";

        }

        //将Image转换成流数据，并保存为byte[]   //imagelist 的size最大256 效果模糊
        public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length); mstream.Close();
            return byData;
        }


        private void button3_Click(object sender, EventArgs e)
        {

            //图片变形要放在document的open()前,否则无效果！！！
            //li.Add(System.Drawing.Image.FromFile("C: \\Users\\Administrator\\Desktop\\QQ浏览器截图\\QQ浏览器截图_20170305111135_A45E7D2B04FA4678B1A2732FDFFA7F48.jpg"));

            if (li.Count > 0)//使用li.Count>0清空后会报错
            {
                Document doc = new Document(PageSize.A4);//A4作为基准
                doc.AddCreationDate();
                doc.AddProducer();
                doc.SetMargins(0, 0, 0, 0);//边距设置为0后就不必强制设定绝对坐标值了SetAbsolutePosition（10，20）;SetAbsolutePosition是从左下角算起的计算也不方便。自然A4大小边缘被裁剪的问题也消失了


                OutPathTemp = OUTdirectory();
                //会有文件同时占用的情况
                PdfWriter.GetInstance(doc, new FileStream(OutPathTemp, FileMode.Create));

                doc.Open();
                for (int i = 0; i <= li.Count - 1; i++)
                {
                    doc.NewPage();
                    try
                    {

                        iTextSharp.text.Image imgTEMP = iTextSharp.text.Image.GetInstance(li[i], System.Drawing.Imaging.ImageFormat.Jpeg);
                        imgTEMP.ScaleToFit(PageSize.A4);
                        doc.Add(imgTEMP);
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }
                doc.Close();
                MessageBox.Show(this, "转换成功！");
                richTextBox1.Text = richTextBox1.Text
                    + System.Environment.NewLine
                    + DateTime.Now.ToLongTimeString()
                    + "转换成功！生成的pdf默认放D盘"
                    + System.Environment.NewLine;
                richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
                richTextBox1.ScrollToCaret();//滚动到插入符号位置

                if (!string.IsNullOrEmpty(OutPathTemp))
                {
                    OpenFolderAndSelectFile(OutPathTemp);

                }

                OutPathTemp = null;//清空临时输出目录
                richTextBox1.Text = richTextBox1.Text
                    + System.Environment.NewLine
                    + DateTime.Now.ToLongTimeString()
                    + "清除输出目录"
                    + System.Environment.NewLine;
                li.RemoveRange(0, li.Count);//清空所有图片缓存,用li = null会报空指针；
                richTextBox1.Text = richTextBox1.Text
                    + System.Environment.NewLine
                    + DateTime.Now.ToLongTimeString()
                    + "清除图片缓存"
                    + System.Environment.NewLine;
                richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
                richTextBox1.ScrollToCaret();//滚动到插入符号位置
            }
            else
            {
                MessageBox.Show("没有东西");
            }
            li.RemoveRange(0, li.Count);//清空所有图片缓存

        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string path = null;//临时转换用路径
                
            //获取文件路径字符串组
            string[] str= e.Data.GetData(DataFormats.FileDrop) as string[];
            //一个个路径拿出来转换
            for (int i=0;i<= str.Length-1;i++) {
                //iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(path);
                //如果拖进来的是文件类型
                path = str[i];
                if (path.Length > 1)
                {
                    FileInfo fil = new FileInfo(path);

                    if (fil.Attributes == FileAttributes.Directory)//文件夹
                    {
                        richTextBox1.Text = richTextBox1.Text

                               + DateTime.Now.ToLongTimeString()
                               + " "
                               + "是文件夹"
                               + System.Environment.NewLine;
                        richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
                        richTextBox1.ScrollToCaret();//滚动到插入符号位置
                    }
                    else
                    {
                        if (iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_BMP
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_GIF
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_BMP
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.JPEG
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.JPEG2000
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.IMGRAW
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_JPEG
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_PNG
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_TIFF
                        | iTextSharp.text.Image.GetInstance(path).OriginalType == iTextSharp.text.Image.ORIGINAL_JPEG2000
                        )
                        {

                            richTextBox1.Text =
                                richTextBox1.Text
                                + System.Environment.NewLine
                                + "在 "
                                + DateTime.Now.ToLongTimeString()
                                + " 时拖放了 "
                                + System.Environment.NewLine
                                + path
                                + System.Environment.NewLine;
                            //string path = pathDrag;
                            //// if(System.Drawing.Image.FromFile(path))
                            li.Add(System.Drawing.Image.FromFile(path));
                            ////MessageBox.Show("拖放成功！");//弹出消息会重复dragenter
                            richTextBox1.Text =
                                richTextBox1.Text
                                + "在 "
                                + DateTime.Now.ToLongTimeString()
                                + "时："
                                + "拖放成功！"
                                + System.Environment.NewLine;
                            richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
                            richTextBox1.ScrollToCaret();//滚动到插入符号位置
                        }
                        else
                        {

                            richTextBox1.Text =
                              richTextBox1.Text
                              + DateTime.Now.ToLongTimeString()
                              + " 没有图片"
                              + System.Environment.NewLine;
                            richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
                            richTextBox1.ScrollToCaret();//滚动到插入符号位置
                        }
                    }
                }
                else {
                    path = null;
                    continue;
                }
            }
            path = null;
           

        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            //延后到dragdrop才发生。

            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }


        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void OpenFolderAndSelectFile(String fileFullName)//打开制定目录
        {
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
            psi.Arguments = "/e,/select," + fileFullName;//Explorer /e 此命令使用默认视图启动 Windows 资源管理器。此命令启动 Windows 资源管理器后选定文件。
            System.Diagnostics.Process.Start(psi);
        }

        private static string dataMilliStr()//格式化好的毫秒数
        {
            //用当前时间作为pdf文件名
            //因为使用“:”与“/”会出错“//”又懒得加
            string strDataMilli =
                DateTime.Now.ToShortDateString().Replace('/', '-')
                + "-"
                + DateTime.Now.ToShortTimeString().Replace(':', '-')
                + "-"
                + DateTime.Now.Millisecond.ToString();
            return strDataMilli;
            //MessageBox.Show(this, strDataMilli);//测试文件名合法性

        }

        private static string OUTdirectory()
        {

            string strFileOutdirectory =
                 "d:\\" + dataMilliStr() + ".pdf";//打包路径名，方便扩展
            return strFileOutdirectory;

        }
        private static void RichTextBox_AddText(string str)
        {

            //richTextBox1.SelectionStart = richTextBox1.TextLength;//设置插入符号位置到末尾
            //richTextBox1.ScrollToCaret();//滚动到插入符号位置
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void richTextBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //双击在log与消息之间变换
            string str_richbox_Temp= richTextBox1.Text;
            richTextBox1.Text = strLog;
            strLog = str_richbox_Temp;
        }
    }
}
